﻿using System;
using System.Web;
using System.Data.SqlClient;
using SQLHelper;

/// <summary>
/// Auth 的摘要说明
/// 第一：判断用户是否登录
/// 第二：检查是否存在cookie
/// 第三：是否为黑名单
/// 第四：检查用户权限
/// 第五：添加权限控制
/// </summary>

namespace Auth
{
    public class NoapAuth
    {
        public int UserID;

        public bool IsForbidden;

        public string Role;

        public string[] Profile;

        // 第一、二
        public void UserIdentification()
        {
            HttpCookie UserAccountCookie = HttpContext.Current.Request.Cookies["NOAP_USER_ACCOUNT"]; // 用户登录时的cookie

            // 首先检查保存用户邮箱和密码的cookie是否存在，存在登录，不存在跳回登录页
            if (UserAccountCookie != null)
            {
                string email = Convert.ToString(UserAccountCookie.Values["NOAP_USER_ACCOUNT_EMAIL"]);
                string password = Convert.ToString(UserAccountCookie.Values["NOAP_USER_ACCOUNT_PASSWORD"]);
                HttpContext.Current.Session["email"] = email;
                HttpContext.Current.Session["password"] = password;
            }

            // 无session,跳回登录页
            if (HttpContext.Current.Session["email"] == null && HttpContext.Current.Session["password"] == null)
            {
                HttpContext.Current.Response.Redirect("~/account/Login.aspx");
            }
        }

        public void Logout()
        {
            if (HttpContext.Current.Request.Cookies["NOAP_USER_ACCOUNT"] != null)
            {
                HttpCookie UserAccountCookie = HttpContext.Current.Request.Cookies["NOAP_USER_ACCOUNT"];
                UserAccountCookie.Expires = DateTime.Now.AddDays(-2);
                HttpContext.Current.Response.Cookies.Add(UserAccountCookie);
            }
            // 使cookie过期，删除cookie，不用关闭浏览器
            HttpContext.Current.Session["email"] = null;
            HttpContext.Current.Session["password"] = null;
        }

        // ============================================================================================
        // ============================================================================================
        // ============================================================================================

        public void OnlyAdmin()
        {
            if (Role != "administrator")
            {
                HttpContext.Current.Response.Redirect("~/403.html");
            }
        }

        public void OnlyAdminAndWriter()
        {
            if (Role != "administrator" || Role != "writer")
            {
                HttpContext.Current.Response.Redirect("~/403.aspx");
            }
        }

        // ============================================================================================
        // ============================================================================================
        // ============================================================================================

        void SetUserID()
        {
            string email = Convert.ToString(HttpContext.Current.Session["email"]);
            string sqlStr = "select id from users where email = '" + email + "'";
            SqlDataReader res = DB.GetDataWithQuery(sqlStr);
            if (res.Read())
            {
                UserID = Convert.ToInt32(res["id"]);
            }
            DB.ColseSqlCon();
        }

        void SetRole()
        {
            string[] rolesArr = new string[3] { "administrator", "writer", "user" };
            int role_id;
            string sqlStr = "select role_id from role_user where user_id = '" + UserID + "'";
            SqlDataReader res = DB.GetDataWithQuery(sqlStr);
            if (res.Read())
            {
                role_id = Convert.ToInt32(res["role_id"]);
                for (int i = 1; i <= 3; i++)
                {
                    if (role_id == i)
                    {
                        Role = rolesArr[i - 1];
                    }
                }
            }
            DB.ColseSqlCon();
        }

        void SetIsForbidden()
        {
            string sqlStr = "select * from blacklist where user_id = '" + UserID + "'";
            SqlDataReader res = DB.GetDataWithQuery(sqlStr);
            if (res.Read())
            {
                IsForbidden = true;
            }
            DB.ColseSqlCon();
        }

        void SetProfile()
        {
            string checkSql = "select id, name, email, created_at, photo, education, location, notes from users where email = '" + HttpContext.Current.Session["email"] + "'";
            SqlDataReader res = DB.GetDataWithQuery(checkSql);
            Profile = new string[8];
            if (res.Read())
            {
                for (int i = 0; i < res.FieldCount; i++)
                {
                    if (Convert.ToString(res[i]) == "")
                    {
                        Profile[i] = "请设置个人信息";
                    }
                    else
                    {
                        Profile[i] = Convert.ToString(res[i]);
                    }
                }
                if (Profile[4] == "请设置个人信息")
                {
                    Profile[4] = "/dist/img/avatar5.png";
                }
            }

            DB.ColseSqlCon();
        }

        public NoapAuth()
        {
            SetUserID();
            SetRole();
            SetIsForbidden();
            SetProfile();

            if (IsForbidden)
            {
                Logout();
                HttpContext.Current.Response.Redirect("~/403.html");
            }
            // TODO: 在此处添加构造函数逻辑
        }
    }
}

